<template>
  <a-card :bordered="false">
    <a-form :form="form">
      <a-row>
        <a-col :sm="12" :xs="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="知识库类型">
            <a-select
              v-decorator="['type', { rules: [{ required: false, message: '请选择咨询类型' }] }]"
              placeholder="请选择咨询类型"
            >
              <a-select-option
                v-for="item in baseType"
                :key="item.key"
                :value="item.key"
              >{{ item.value }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :sm="12" :xs="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="标题">
            <a-input
              v-decorator="['tittle', { rules: [{ required: true, message: '请输入标题', trigger: 'blur' }]
                }]"
              placeholder="请输入标题"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :sm="12" :xs="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="关键字类型">
            <a-select mode="tags" placeholder="请输入关键字类型" v-decorator="['keywords', { rules: [{ required: false, message: '请选择关键词' }] }]">
              <a-select-option
                v-for="item in  keyWordsList"
                :key="item"
                :value="item"
              >{{ item }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :sm="12" :xs="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="原文链接">
            <a-input
              v-decorator="['url', { rules: [{ required: false, message: '请输入原文链接', trigger: 'blur' }]
                }]"
              placeholder="请输入原文链接"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :sm="12" :xs="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="文件上传">
            <a-upload-dragger
              :file-list="fileList"
              name="file"
              :multiple="false"
              :remove="handleRemove"
              :before-upload="beforeUpload"
            >
              <p class="ant-upload-drag-icon">
                <a-icon type="inbox"/>
              </p>
              <p class="ant-upload-text">
                请轻击此处选择文件或将文件直接拖拽进框内
              </p>
              <p class="ant-upload-hint">
                支持单文件上传
              </p>
            </a-upload-dragger>
          </a-form-item>
        </a-col>
        <a-col :sm="12" :xs="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="文件描述">
            <a-textarea v-decorator="['content', { rules: [{ required: false, message: '请输入文件描述', trigger: 'blur' }]
                }]"  placeholder="请输入文件描述" :rows="6" style="margin-top: 5px;"/>
          </a-form-item>
        </a-col>

      </a-row>

    </a-form>
    <a-row class="BottomButtons">
      <span>
        <a-button size="large" type="primary" @click="handleOk">提交</a-button>
        <!--            <a-button type="default" @click="handleCancel">取消</a-button>-->
      </span>
    </a-row>

    <a-modal v-model="modalShow" :title="modalTitle" ok-text="确认" cancel-text="取消" @ok="hideModal">
      <div style='display: flex;justify-content: center;align-items: center'>
        <p style='word-break: keep-all;margin: 0 30px 0'>模板名称</p>
        <a-input style='width: 300px'/>
      </div>
    </a-modal>
  </a-card>
  <!--  </a-spin>-->
  <!--  </j-modal>-->
</template>

<script>
import { getAction, httpAction } from '@/api/manage'
import axios from 'axios'
import qs from 'qs'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { mapGetters } from 'vuex'

export default {
  name: 'newKnowledge',
  data() {
    return {
      modalShow: false,
      modalTitle: '另存为模板',
      selectList: [
        {
          id: 1,
          option: '2021款汉DMI'
        },
        {
          id: 2,
          option: '选项1'
        },
        {
          id: 3,
          option: '选项2'
        },
        {
          id: 4,
          option: '选项3'
        }
      ],
      title: '交易信息',
      visible: false,
      model: {},
      fileList: [],
      noChooseBrand: true,
      loading: '',
      loading2: '',
      loading3: '',
      loading4: '',
      saleSource: [],
      SaleInfosLike: [],
      keyWordsList: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      imageUrl: '',
      imageUrl2: '',
      imageUrl3: '',
      imageUrl4: '',
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {},
      url: {
        add: '/cxm/knowledgeBase/add',
        edit: '/sale/cxmSaleCarInfo/editCarInfo',
        imgAction: 'cxm/cxmCommonBusiness/uploadPlainText',
        delete: '/sale/cxmSaleCarInfo/delete'
      },
      showDing: false,
      showEnterpriseUscc: false,
      headers: '',
      picData: {},
      storeName: [],
      storeId: [],
      selectItem: [1, 2, 3, 4, 5],
      baseType: [
        {
          key: 1,
          value: '政策文件类'
        }, {
          key: 2,
          value: '申请流程类'
        }, {
          key: 3,
          value: '需求咨询类'
        }, {
          key: 4,
          value: '建议意见类'
        }, {
          key: 5,
          value: '投诉举报类'
        }
      ],
      handlingStatus: [
        {
          key: 1,
          value: '待处理'
        }, {
          key: 2,
          value: '已处理'
        }
      ],
      file: '',
      storekeeperName: [],
      storekeeperId: [],
      checkboxgroupvalue: [],
      checkboxgroupvalue2: [],
      brandList: [],
      brandListAll: [],
      colorList: [],
      carModel: [],
      carModelAll: [],
      inColorList: [],
      supplierList: {},
      manufacturerList: {},
      shouxuList: [],
      zhuangbeiList: [],
      appearanceImg: '',
      qrCodeImg: '',
      nameplateImg: '',
      certificateImg: ''
    }
  },
  created() {
    const token = Vue.ls.get(ACCESS_TOKEN)
    // this.headers = { 'X-Access-Token': token, 'Content-Type': 'application/x-www-form-urlencoded' }
    this.headers = { 'X-Access-Token': token }
    getAction('/cxm/knowledgeBase/getKeyWords', {})
      .then((res) => {
        console.log(res)
        if (res.success) {
          // console.log(res)
          this.keyWordsList = res.result
          console.log( this.keyWordsList)
        }

      })
  },
  computed: {
    importImgAction: function() {
      return `${process.env.VUE_APP_BASE_API}${this.url.imgAction}`
    }
  },
  methods: {
    upload(file) {
      console.log(file)
      let fileList = this.fileList

      // 1. Limit the number of uploaded files
      //    Only to show two recent uploaded files, and old ones will be replaced by the new
      if (fileList.length > 1) {
        fileList = fileList.slice(-1)
        this.$message.warning('仅允许上传单份文件，已覆盖原文件')
      }

      // 2. read from response and show file link
      fileList = fileList.map(file => {
        if (file.response) {
          // Component will show file.url as link
          file.url = file.response.url
        }
        return file
      })

      this.fileList = fileList
      console.log(this.fileList)
      this.file = file
      console.log(this.file)

    },
    ...mapGetters(['nickname', 'avatar', 'userInfo']),
    showModal() {
      this.modalShow = true
    },
    hideModal() {
      this.modalShow = false
    },
    beforeUpload(file) {
      this.fileList = [...this.fileList, file]
      console.log(this.fileList)
      this.upload(file)
      return false
    },
    handleRemove(file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
    },

    add(record) {
      console.log(record)
      this.edit(record)
    },
    edit(record) {

      this.form.resetFields()
      this.model = Object.assign({}, record)
      console.log(this.model)
      this.visible = true


      this.$nextTick(() => {

        this.form.setFieldsValue({
          /* 基本信息： */
          supplier: this.model.supplier,
          manufacturer: this.model.manufacturer,
          storeId: this.model.storeId,
          storekeeperId: this.model.storekeeperId,
          /* 车辆信息： */
          vin: this.model.vin,
          certificateNo: this.model.certificateNo,
          brand: this.model.brand,
          carModel: this.model.carModel,
          carTypeConfiguration: this.model.carTypeConfiguration,
          powerType: this.model.powerType,
          fuelType: this.model.fuelType,
          outsideColor: this.model.outsideColor,
          interiorColor: this.model.interiorColor,
          engineModel: this.model.engineModel,
          engineNo: this.model.engineNo,
          displacement: this.model.displacement,
          gearbox: this.model.gearbox,
          tireNo: this.model.tireNo,
          passengerCapacity: this.model.passengerCapacity ? String(this.model.passengerCapacity) : null,
          motorPower: this.model.motorPower,
          emissionStandards: this.model.emissionStandards,
          wheelbase: this.model.wheelbase,
          loadQuality: this.model.loadQuality,
          batteryNo: this.model.batteryNo,
          /* 上传图片 ： */
          appearanceImg: this.model.appearanceImg,
          qrCodeImg: this.model.qrCodeImg,
          nameplateImg: this.model.nameplateImg,
          certificateImg: this.model.certificateImg
        })
      })
    },
    close() {
      this.$emit('close')
      this.imageUrl = null
      this.imageUrl1 = null
      this.imageUrl2 = null
      this.imageUrl3 = null
      this.imageUrl4 = null
      this.appearanceImg = null
      this.qrCodeImg = null
      this.nameplateImg = null
      this.certificateImg = null
      this.visible = false

      this.fileList = []
      this.model = {}
      this.form.resetFields()
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {

        if (!err && this.fileList.length> 0) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'post'
          }
          // this.model.keywords = this.model.keywords ? this.model.keywords.join(',') : null
          console.log(values)
          let formData = new FormData()
          // 赋值与判空
          if (this.fileList !== []) {
            formData.append('file', this.fileList[0])
          }
          if (values.tittle){
            formData.append('tittle', values.tittle)
            //后端字段为tittle不是title
          }
          if(values.url){
            formData.append('url', values.url)
          }
          if (values.type) {
            formData.append('type', values.type)
          }
          if (values.keywords) {
            formData.append('keywords', values.keywords)
          }
          if (values.content) {
            formData.append('content', values.content)
          }
          //时间格式化
          /* formData.orderDate = formData.orderDate ? formData.orderDate.format('YYYY-MM-DD HH:mm:ss') : null */
          //formData.shouxuList = this.checkboxgroupvalue;
          httpAction(this.url.add, formData, method)
            .then((res) => {
              console.log(res)
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
              this.noChooseBrand = true
              that.close()
            })
        }else {
          this.$message.warning('请上传文件')
        }
      })
    },
    handleCancel() {
      this.close()
    },
    onChange(checkedValues) {
      console.log('checked = ', checkedValues)
      console.log('value = ', this.value)
    },
    onChange2(checkedValues) {
      console.log('checked = ', checkedValues)
      console.log('value = ', this.value)
    },
    changeBrand(value) {
      this.carModel = []
      this.form.setFieldsValue({
        'carModel': []
      })
      this.noChooseBrand = false
      for (let i = 0; i < this.brandListAll.length; i++) {
        if (this.brandListAll[i].name == value) {
          for (let j = 0; j < this.carModelAll.length; j++) {
            if (this.carModelAll[j].parentId == this.brandListAll[i].id) {
              this.carModel.push(this.carModelAll[j].name)
            }
          }
        }
      }
    }
  }
}
</script>

<style scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.ant-upload-select-picture-card img {
  width: 128px;
  height: 128px;
}

.BottomButtons {
  text-align: center;
  margin-top: 70px;
}

.titleText {
  margin: 0 0 15px 5%;
}
</style>